﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Graph = Microsoft.Office.Interop.Graph;
using System.Runtime.InteropServices;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System.Windows.Forms;
using System.Windows;
using Media = System.Windows.Media;
using Microsoft.Office.Interop.Word;
using D=System.Drawing;
namespace DataLayer
{
    public class Converter
    {
        public static Node SlideToNode(PowerPoint.Slide slide)
        {
            Node rs = new Node();
            return rs;
        }


        public static MindMap PP2Mindmap(string _ppPath,ref int percent, string projectPath)
        {
            MindMap rs = new MindMap();

            PowerPoint.Application objApp;
            PowerPoint.Presentations objPresSet;
            PowerPoint._Presentation objPres;
            objApp = new PowerPoint.Application();
            //objApp.Visible = MsoTriState.msoTrue;
            objPresSet = objApp.Presentations;

            objPres = objPresSet.Open(_ppPath,
                MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
            PowerPoint.Slides objSlides;
            PowerPoint._Slide objSlide;
            objSlides = objPres.Slides;
            int count = objSlides.Count;

            string activeDir = projectPath + @"/resource/image";
            string newPath = System.IO.Path.Combine(activeDir, objPres.Name);
            System.IO.Directory.CreateDirectory(newPath);


            RootNode rootnote = new RootNode();

            rootnote.Color = (Media.Color)Media.ColorConverter.ConvertFromString("#ff111111");
            List<SystemFile> listResources = ResourcesHelper.GetInstance().ListObject;
            int unitPercent = (int)100/count;

            RichTextBox rTextBox = new RichTextBox();
                             
            for (int i = 1; i <= count; i++)
            {
                percent += unitPercent;
                Node node;
                if (i == 1)
                    node = rootnote;
                else
                    node = new Node();

                node.Color = (Media.Color)Media.ColorConverter.ConvertFromString("#ff111111");
                node.Name = "Slide " + i;
                objSlide = objSlides._Index(i);

                for (int j = 1; j <= objSlide.Shapes.Count; j++)
                {
                    PowerPoint.Shape shape = objSlide.Shapes[j];


                    if (shape.Type == MsoShapeType.msoPlaceholder)
                    {
                        if (j == 1)
                        {
                            if (objSlide.Shapes.HasTitle == MsoTriState.msoTrue)
                            {
                                node.Name = objSlide.Shapes.Title.TextFrame.TextRange.Text;
                            }
                            else
                            {
                                node.Name = shape.TextFrame.TextRange.Text;
                            }
                           continue;
                        }
                        
                            try
                            {
                                //shape.    
                                PowerPoint.TextRange textrange = shape.TextFrame.TextRange;
                                TextContent content = new TextContent();
                                content.Type = "text";
                                content.Left = shape.Left;
                                content.Top = shape.Top;
                                content.Width = shape.Width;
                                content.Height = shape.Height;
                                int paragraphCount = textrange.Paragraphs().Count;
                                for (int p = 1; p <= paragraphCount; p++)
                                {
                                    PowerPoint.TextRange paragraph = textrange.Paragraphs()._Index(p);
                                    rTextBox.Clear();
                                    rTextBox.AppendText(paragraph.Text);
                                    string text = rTextBox.Rtf;
                                    Paragraph myParagraph = new Paragraph(text);
                                    myParagraph.FontName = paragraph.Font.Name;
                                    myParagraph.FontSize = paragraph.Font.Size;
                                    if (paragraph.IndentLevel < 5)
                                        myParagraph.IndentLevel = paragraph.IndentLevel;
                                    else
                                        myParagraph.IndentLevel = 5;
                                    PowerPoint.BulletFormat bullet = textrange.ParagraphFormat.Bullet;

                                    PowerPoint.PpBulletType type = bullet.Type;
                                    myParagraph.Color = paragraph.Font.Color.RGB;
                                    if (type == PowerPoint.PpBulletType.ppBulletNumbered)
                                    {
                                        myParagraph.BulletType = 1;
                                        myParagraph.BulletValue = bullet.Number;
                                    }
                                    else
                                    {
                                        if (type == PowerPoint.PpBulletType.ppBulletUnnumbered)
                                        {
                                            myParagraph.BulletType = 2;
                                            myParagraph.BulletValue = bullet.Character;
                                        }
                                        else
                                        {
                                            myParagraph.BulletType = 0;

                                        }
                                    }
                                    content.AddParagraph(myParagraph);
                                }

                                if (shape.TextEffect.Alignment == MsoTextEffectAlignment.msoTextEffectAlignmentCentered)
                                {
                                    content.Alignment = 1;
                                }
                                if (shape.TextEffect.Alignment == MsoTextEffectAlignment.msoTextEffectAlignmentLeft)
                                {
                                    content.Alignment = 0;
                                }
                                if (shape.TextEffect.Alignment == MsoTextEffectAlignment.msoTextEffectAlignmentRight)
                                {
                                    content.Alignment = 2;
                                }
                                node.AddContent(content);
                            }
                            catch (Exception ex)
                            {
                                //MessageBox.Show(ex.Message);
                            }
                        
                    }
                    else
                    {
                        try
                        {
                            if (!System.IO.File.Exists(newPath + "/slide" + i + ".png"))
                            {
                                objSlide.Export(newPath + "/slide" + i + ".png", "png");
                            }


                            D.Bitmap bitmap = new D.Bitmap(newPath + "/slide" + i + ".png");
                            D.Bitmap newbitmap = CropBitmap(bitmap, (int)shape.Left, (int)shape.Top, (int)shape.Width, (int)shape.Height);
                            newbitmap.Save(newPath + "/slide" + i + "-shape" + j + ".png");
                            //Resource resource = new Resource();
                            //resource.Id = listResources.Count;
                            //resource.Type = 1;//type of image is 1
                            //resource.Path = newPath + "/slide" + i + "-shape" + j + ".png";
                            //listResources.Add(resource);
                            bitmap.Dispose();
                            newbitmap.Dispose();
                            ImageContent content = new ImageContent(newPath + "/slide" + i + "-shape" + j + ".png");
                            content.Type = "image";
                            content.Left = shape.Left;
                            content.Top = shape.Top;
                            content.Width = shape.Width;
                            content.Height = shape.Height;
                            node.AddContent(content);
                        }
                        catch { }

                    }

                }
                ResourcesHelper.GetInstance().Update();
                if (i != 1)
                {
                    node.CheckLevel();
                    node.CheckContent();
                    
                    rootnote.AddNode(node);
                }
            }
            rootnote.Name = objPres.Name;
            rs.RootNode = rootnote;
            rootnote.CheckChildNode();
            
            //rs.createPP();
            percent = 100;
            return rs;
        }     



        private static D.Bitmap CropBitmap(D.Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
        {
            if (cropHeight == 0)
                cropHeight = 1;
            if (cropWidth == 0)
                cropWidth = 1;
            if (cropX + cropWidth > bitmap.Width)
            {
                cropWidth -= cropX + cropWidth - bitmap.Width;
            }
            if (cropY + cropHeight > bitmap.Height)
            {
                cropHeight -= cropY + cropHeight - bitmap.Height;
            }
            D.Rectangle rect = new D.Rectangle(cropX, cropY, cropWidth, cropHeight);
            D.Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);

            return cropped;
        }
        public static int CountSlides(string presentationFile)
        {
            // Open the presentation as read-only.
            using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
            {                
                return CountSlides(presentationDocument);
            }
        }

        public static int CountSlides(PresentationDocument presentationDocument)
        {
            // Check for a null document object.
            if (presentationDocument == null)
            {
                throw new ArgumentNullException("presentationDocument");
            }

            int slidesCount = 0;

            // Get the presentation part of document.
            PresentationPart presentationPart = presentationDocument.PresentationPart;
            // Get the slide count from the SlideParts.
            if (presentationPart != null)
            {
                slidesCount = presentationPart.SlideParts.Count();
            }
            // Return the slide count to the previous method.
            return slidesCount;
        }


    }
}
